package com.cs171.market.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cs171.market.Repository.UserRepository;
import com.cs171.market.annotation.UserLoginToken;
import com.cs171.market.entity.Student;
import com.cs171.market.entity.User;
import com.cs171.market.entity.UserTable;
import com.cs171.market.mapper.UserMapper;
import com.cs171.market.service.TokenService;
import com.cs171.market.service.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.lettuce.core.dynamic.annotation.Param;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.jws.soap.SOAPBinding;
import java.util.List;
import java.util.logging.Logger;

/**
 * @author Endy
 * @create 2020 - 05 - 21 - 20:50
 * @date 2020/5/21 - 20:50
 * User(用户)控制层
 */

@RestController
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    TokenService tokenService;
    @Autowired
    UserRepository userRepository;
    @Autowired
    UserMapper userMapper;
    @CrossOrigin

    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public Object login(@RequestParam("username")String username,@RequestParam("password")String password){
        JSONObject jsonObject = new JSONObject();
        User userForBase = userRepository.findByUsername(username);
        if (userForBase == null){
            jsonObject.put("message","failed to login! user not exist");
        }
        else {
            if (!userForBase.getUpassword().equals(password)){
                jsonObject.put("message","failed to login! wrong password");
            }else {
                Integer success=200;
                JSONObject metaObject = new JSONObject();
                metaObject.put("msg","登陆成功");
                metaObject.put("status",success);
                String token = tokenService.getToken(userForBase);
                User userObject = userMapper.userLoginByName(userForBase.getUid());
                userObject.setToken(token);
                jsonObject.put("user", userObject);
                jsonObject.put("meta",metaObject);
            }
        }
        return jsonObject;
        //return 1;
    }


    /**
     * 用户数据列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/users")
    public Object allUsers(@RequestParam(value = "pageNum", defaultValue = "1")Integer pageNum,
                           @RequestParam(value = "pageSize", defaultValue = "5")Integer pageSize){
        //pageNum--总共的页数
        Integer success=200;
        PageHelper.startPage(pageNum,pageSize);
        //List<User> users = userRepository.findByAllUser();
        Page<UserTable> userList = userMapper.new_getUserList();
        PageInfo<UserTable> pageInfo = new PageInfo<>(userList);
        JSONObject jsonObject = new JSONObject();
        JSONObject metaObject = new JSONObject();
        JSONObject dataObject = new JSONObject();
        metaObject.put("msg","获取用户列表成功");
        metaObject.put("status",success);
        JSONArray Users = (JSONArray)JSON.toJSON(userList);
        dataObject.put("users",Users);
        dataObject.put("pagenum",pageInfo.getPageNum());
        dataObject.put("total",userMapper.countUser());
        jsonObject.put("data",dataObject);
        jsonObject.put("meta",metaObject);
        return jsonObject;
    }

    /**
     * 用户添加
     * @return
     */
    @PostMapping("/users")
    public Object addUsers(@RequestParam(value = "username") String userName, @RequestParam(value = "password") String passWord,
                           @RequestParam(value = "email", required = false) String uEmail, @RequestParam(value = "mobile", required = false) String uMobile)
    {
        User newUser = new User();
        newUser.setUname(userName);
        newUser.setUpassword(passWord);
        newUser.setUemail(uEmail);
        newUser.setUphone(uMobile);
        userRepository.save(newUser);

        Integer success = 200;

        User user = userRepository.findByUsername(userName);
        JSONObject jsonObject = new JSONObject();
        JSONObject metaObject = new JSONObject();
        metaObject.put("msg","创建成功");
        metaObject.put("status",success);
        jsonObject.put("data",user);
        jsonObject.put("meta",metaObject);
        return jsonObject;
    }




    //getAll测试
    @GetMapping("/all")
    private List<User> getall(){
        return userRepository.findAll();
    }


    @GetMapping("/users/{id}")
    public Object findById(@PathVariable("id")Integer id){
        Integer success = 200;
        JSONObject jsonObject = new JSONObject();
        JSONObject metaObject = new JSONObject();
        UserTable user = userMapper.getUserById(id);
        metaObject.put("msg","查询成功");
        metaObject.put("status",success);
        jsonObject.put("data",user);
        jsonObject.put("meta",metaObject);
        return jsonObject;
    }

    @PutMapping("/users/{id}")
    public Object updateById(@PathVariable("id")Integer id, @RequestParam(value = "email", required = false)String new_email,
                             @RequestParam(value = "phone", required = false)String new_phone){
        Integer success = 200;
        JSONObject jsonObject = new JSONObject();
        JSONObject metaObject = new JSONObject();
        userMapper.updateUserById(id,new_email,new_phone);
        UserTable user = userMapper.getUserById(id);
        metaObject.put("msg","更新成功");
        metaObject.put("status",success);
        jsonObject.put("data",user);
        jsonObject.put("meta",metaObject);
        return jsonObject;
    }

    @PutMapping("/users/{id}/state/{type}")
    public Object changeStateById(@PathVariable("id")Integer id,@PathVariable("type")boolean type)
    {
        Integer success = 200;
        JSONObject jsonObject = new JSONObject();
        JSONObject metaObject = new JSONObject();
        Integer new_state = type ? 1 : 0;
        userMapper.updateStateById(id,new_state);
        UserTable user = userMapper.response_updateState(id);
        metaObject.put("msg","设置状态成功");
        metaObject.put("status",success);
        jsonObject.put("data",user);
        jsonObject.put("meta",metaObject);
        return jsonObject;
    }

    @DeleteMapping("users/{id}")
    public Object deleteById(@PathVariable("id")Integer id)
    {
        Integer success = 200;
        JSONObject jsonObject = new JSONObject();
        JSONObject metaObject = new JSONObject();
        userMapper.deleteById(id);
        metaObject.put("msg","删除成功");
        metaObject.put("status",success);
        jsonObject.put("data","null");
        jsonObject.put("meta",metaObject);
        return jsonObject;
    }

    @PutMapping("users/{id}/role")
    public Object changeRoleById(@PathVariable("id")Integer id, Integer rid)
    {
        Integer success = 200;
        JSONObject jsonObject = new JSONObject();
        JSONObject metaObject = new JSONObject();
        userMapper.changeRoleById(id, rid);
        UserTable user = userMapper.response_changeRole(id);
        metaObject.put("msg","设置角色成功");
        metaObject.put("status",success);
        jsonObject.put("data",user);
        jsonObject.put("meta",metaObject);
        return jsonObject;
    }


    @GetMapping("/username/{name}")
    public User findByUsername(@PathVariable("name")String username){
        return userRepository.findByUsername(username);
    }


}
